package com.gitee.wsl.ext.collection


/**
 * Returns a [Map] containing key-value pairs provided by [key] and [value] functions
 * applied to elements of the given sequence.
 *
 * If any of two pairs would have the same key the first one gets added to the map.
 *
 * The returned map preserves the entry iteration order of the original sequence.
 *
 * The operation is _terminal_.
 */
inline fun <T, K, V> Sequence<T>.associateFirst(
    key: (T) -> K,
    value: (T) -> V,
): Map<K, V> {
    val dst = LinkedHashMap<K, V>()
    for (element in this) {
        val newKey = key(element)
        if (!dst.containsKey(newKey)) {
            dst[newKey] = value(element)
        }
    }
    return dst
}

/**
 * Returns a [Map] containing key-value pairs provided by [key] and [value] functions
 * applied to elements of the given collection.
 *
 * If any of two pairs would have the same key the first one gets added to the map.
 *
 * The returned map preserves the entry iteration order of the original collection.
 */
inline fun <T, K, V> Iterable<T>.associateFirst(
    key: (T) -> K,
    value: (T) -> V,
): Map<K, V> {
    val dst = LinkedHashMap<K, V>()
    for (element in this) {
        val newKey = key(element)
        if (!dst.containsKey(newKey)) {
            dst[newKey] = value(element)
        }
    }
    return dst
}
